package ru.home.documentmanager.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import ru.home.documentmanager.dao.UserDAO;
import ru.home.documentmanager.model.dto.UserModel;
import ru.home.documentmanager.model.security.Role;
import ru.home.documentmanager.model.security.UserRole;

public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private UserDAO userDAO;

    @Transactional
    public UserDetails loadUserByUsername(final String username)
            throws UsernameNotFoundException {
        ru.home.documentmanager.model.User user = userDAO
                .findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        List<GrantedAuthority> authorities = buildUserAuthority(user
                .getUserRole());
        return buildUserForAuthentication(user, authorities);
    }

    private User buildUserForAuthentication(
            ru.home.documentmanager.model.User user,
            List<GrantedAuthority> authorities) {
        return new UserModel(user, true, true, true, authorities);
    }

    private List<GrantedAuthority> buildUserAuthority(UserRole userRole) {
        Role[] roles = userRole.getRoles();
        List<GrantedAuthority> authorities = new ArrayList<>(roles.length);
        for (Role role : roles) {
            authorities.add(role);
        }
        return authorities;
    }

}
